/**
 * 获取用户列表
 * @url admin/system/user/sys/getList
 * @description 获取用户列表，支持分页和搜索
 */
module.exports = {
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: '' };
		
		// 业务逻辑开始-----------------------------------------------------------
		let {
			pageIndex = 1,
			pageSize = 20,
			keyword = '',
			status,
			role_id,
			orderBy = 'last_login_date',
			orderType = 'desc'
		} = data;
		
		// 构建查询条件
		let where = {};
		if (keyword) {
			where = _.or([
				{ username: new RegExp(keyword, 'i') },
				{ nickname: new RegExp(keyword, 'i') },
				{ mobile: new RegExp(keyword, 'i') },
				{ email: new RegExp(keyword, 'i') }
			]);
		}
		if (status !== undefined && status !== null) {
			where.status = status;
		}
		
		// 构建查询
		let query = db.collection('uni-id-users')
			.where(where)
			.field('username,nickname,mobile,email,role,status,last_login_date,avatar,create_date,dcloud_appid');
		
		// 排序
		if (orderBy) {
			query = query.orderBy(orderBy, orderType);
		}
		
		// 分页
		query = query.skip((pageIndex - 1) * pageSize).limit(pageSize);
		
		// 查询用户列表
		let userRes = await query.get();
		
		// 获取总数
		let countRes = await db.collection('uni-id-users').where(where).count();
		
		// 处理角色信息
		let userIds = userRes.data.map(item => item._id);
		let roleRes = await db.collection('uni-id-roles').get();
		let roleMap = {};
		roleRes.data.forEach(role => {
			roleMap[role.role_id] = role.role_name;
		});
		
		// 处理用户数据
		userRes.data.forEach(user => {
			// 处理角色信息
			if (Array.isArray(user.role)) {
				user.role_list = user.role.map(r => {
					if (typeof r === 'string') {
						return roleMap[r] || r;
					}
					return roleMap[r.role_id] || r.role_name || r;
				});
				user.role_display = user.role_list.join('、');
			} else {
				user.role_list = [];
				user.role_display = '';
			}
			
			// 处理应用ID
			if (Array.isArray(user.dcloud_appid)) {
				user.dcloud_appid_display = user.dcloud_appid.join('、');
			} else {
				user.dcloud_appid_display = user.dcloud_appid || '';
			}
		});
		
		// 如果指定了角色筛选（在内存中筛选，因为role是关联字段）
		if (role_id) {
			userRes.data = userRes.data.filter(user => {
				return user.role && user.role.some(r => {
					if (typeof r === 'string') {
						return r === role_id;
					}
					return r.role_id === role_id;
				});
			});
		}
		
		res.data = {
			list: userRes.data,
			total: countRes.total,
			pageIndex,
			pageSize
		};
		
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}

